﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using l1cs.server.model.Instance;

namespace l1cs.server.serverpackets
{
    public class S_PetList : ServerBasePacket
    {
        private static Logger _log = Logger.getLogger( typeof( S_PetList ).FullName );
 
        private byte[] _byte = null;

        public S_PetList( int npcObjId, L1PcInstance pc )
        {
            buildPacket( npcObjId, pc );
        }

        private void buildPacket( int npcObjId, L1PcInstance pc )
        {
            List<L1ItemInstance> amuletList = new List<L1ItemInstance>();
            foreach ( Object itemObject in pc.getInventory().getItems() )
            {
                L1ItemInstance item = (L1ItemInstance)itemObject;
                if ( item.getItem().getItemId() == 40314
                        || item.getItem().getItemId() == 40316 )
                {
                    if ( !isWithdraw( pc, item ) )
                    {
                        amuletList.Add( item );
                    }
                }
            }
            if ( amuletList.Count != 0 )
            {
                writeC( Opcodes.S_OPCODE_SELECTLIST );
                writeD( 0x00000046 ); // Price
                writeH( amuletList.Count );
                foreach ( L1ItemInstance item in amuletList )
                {
                    writeD( item.getId() );
                    writeC( item.getCount() );
                }
            }
        }

        private bool isWithdraw( L1PcInstance pc, L1ItemInstance item )
        {
            //Object[] petlist = pc.getPetList().values().toArray();
            foreach ( Object petObject in pc.getPetList().Values )
            {
                if ( petObject is L1PetInstance )
                {
                    L1PetInstance pet = (L1PetInstance)petObject;
                    if ( item.getId() == pet.getItemObjId() )
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        override
        public byte[] getContent()
        {
            if ( _byte == null )
            {
                _byte = getBytes();
            }
            return _byte;
        }

        override
        public String getType()
        {
            return "[S] S_PetList";
        }
    }
}
